import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import { renderValveOpen, renderSignalIntensity, afterCloseModal } from '@/utils/utils';
import debounce from 'lodash/debounce';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import request from '@/utils/request';
import Setting from "@/pages/MeterWarm/Setting";
import Detail from './../Meters/Detail'
import Meters from "./Meters";

const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ consumption_plan, loading, global }) => ({
  consumption_plan,
  global,
  loading: loading.models.consumption_plan,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      consumption_plan: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        consumption_plan: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'consumption_plan/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'consumption_plan/changeLoaded',
          });
          dispatch({
            type: 'consumption_plan/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'consumption_plan/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'consumption_plan/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'consumption_plan/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          consumption_plan: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      },
    });
  };
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      consumption_plan: { searchParams },
    } = this.props;
    const username=sessionStorage.getItem('username')

    return (
      <Form layout="inline" className="search-form">
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '120px' }} allowClear disabled={Boolean(username==='宁波水表'||username==='竞达水表'||username==='西安旌旗'||username==='泰安水表'||username==='泰安新贝水表')}>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="安装地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="IMEI">
          {getFieldDecorator('imei', {
            initialValue: searchParams.imei,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
    {/*    <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        consumption_plan: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'consumption_plan/add',
      payload: {
        ...formValues,
        install_date: formValues.install_date ? moment(formValues.install_date).format('YYYY-MM-DD') : '',
      },
      callback() {
        message.success('添加水表成功');
        that.setState({
          addModal: false,
        });
        const {
          consumption_plan: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleFormReset = () => {
    const { form } = this.props;
    const username=sessionStorage.getItem('username')
    form.resetFields();
    let vendor_id='';
    if(username==='宁波水表'){
      vendor_id='274576011256434688'
    }else if(username==='竞达水表'){
      vendor_id='270602198973857792'
    }else if(username==='西安旌旗'){
      vendor_id='124590517324547876'
    }else if(username==='泰安水表'){
      vendor_id='124590517324752831'
    }else if(username==='泰安新贝水表'){
      vendor_id='364715278489198597'
    }
    this.handleSearch({
      number: '',
      user_number: '',
      caliber:'',
      address: '',
      vendor_id:vendor_id,
      communication_type:'',
      status:'1',
      page: 1,
      per_page: 50,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `consumption_plan/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        install_date: formValues.install_date ? moment(formValues.install_date).format('YYYY-MM-DD') : '',
      },
      callback() {
        message.success('修改水表成功');
        that.setState({
          editModal: false,
        });
        const {
          consumption_plan: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `consumption_plan/remove`,
      payload: { id },
      callback: () => {
        message.success('删除水表成功');
        const {
          consumption_plan: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleSetting=()=>{
    const formValues = this.imeiForm.props.form.getFieldsValue();
    const that = this;
    let company_id=sessionStorage.getItem('company_id');
    request(`/configs`,{
      method:'PUT',
      data:{
        "config": {
          ...formValues,
        },
        "company_id": company_id,
      }
    }).then((response)=>{
      if(response.status===200){
        message.success('修改报警设置成功');
        that.setState({
          settingModal: false,
        });
        const {
          meter_warm: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  render() {
    const that = this;
    const {
      consumption_plan: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username');
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            consumption_plan: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '水表号',
        width: 150,
        frozen:true,
        key: 'number',

      },
      {
        name: '安装地址',
        frozen:true,
        key: 'address',
        width: 200,
      },
/*      {
        name: '口径',
        key: 'address',
        width: 100,
      },*/
      {
        name: '阀门状态',
        key: 'valve_status',
        width: 100,
        formatter: (event) => {
          return renderValveOpen(event.value);
        },
      },
      {
        name: '水表厂商名称',
        key: 'vendor_name',
        width: 130,
      },
      {
        name: '协议名称',
        key: 'protocol_name',
        width: 150,
      },
      {
        name: '最新读值(m³)',
        key: 'latest_value',
        width: 100,
      },
      {
        name: '操作',
        width: 480,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>用水量设置</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item  animated fadeInLeft">
            <p >已设置报警水表数(个)</p>
            <h4 >{meta.total}</h4>
          </div>
            <div size="large" className="table-info-right-item"  style={{marginBottom:'28px'}}>
              <Button
                icon="plus"
                style={{ marginLeft: 8 }}
                type="primary"
                className={'btn-cyan'}
                onClick={
                  () => {
                    this.setState({
                      meterModal: true,
                    });
                  }
                }
              >
                添加水表报警
              </Button>
              <Button
                icon="setting"
                style={{ marginLeft: 8 }}
                type="primary"
                onClick={
                  () => {
                    this.setState({
                      settingModal: true,
                    });
                  }
                }
              >
                系统报警设置
              </Button>
            </div>
        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (index,row) => {
                if (!row) {
                  return;
                }
                this.props.dispatch({
                  type: 'consumption_plan/changeSelectRow',
                  payload:[index],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          consumption_plan: {  scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop =0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.settingModal} modalClass="settingModal"
                                title={`报警设置`}/>}
        destroyOnClose
        visible={this.state.settingModal}
        centered
        onOk={this.handleSetting}
        className="settingModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ settingModal: false, editRecord: {} });
        }}

      >
        <Setting editRecord={this.state.editRecord}
                 wrappedComponentRef={(inst) => this.imeiForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.meterModal} modalClass="meterModal" title="设置水表"/>}
        className="meterModal"
        visible={this.state.meterModal}
        centered
        width={1250}
        onCancel={()=> {
          this.setState({meterModal: false})
        }}
        footer={null}
      >
        <Meters
          handleSearch={()=>{
            const {
              consumption_plan: {searchParams },
            } = this.props;
            this.handleSearch(searchParams)
          }
          }
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>

    </div>;
  }
}

export default BasicList;
